#include "Model.h"

#include <fstream>

#define GLEW_STATIC

#include <glew.h>
#ifdef _WIN32
#include <wglew.h>
#include <GL/GL.h>
#else
#include <GL/gl.h>
#endif

le::Model::Model()
: m_Vertices(NULL)
, m_NumVertices(0)
, m_NumIndices(0)
{
	// TODO: This is just some debug code
	m_NumVertices = 3;
	m_NumIndices = 3;
	m_Vertices = new le::Model::VertexType[m_NumVertices];

	m_Vertices[0].vertexPos.x = -1.0f;  // Position.
	m_Vertices[0].vertexPos.y = -1.0f;
	m_Vertices[0].vertexPos.z =  0.0f;

	m_Vertices[0].color.x = 1.0f;  // Color.
	m_Vertices[0].color.y = 0.0f;
	m_Vertices[0].color.z = 0.0f;

	// Top middle.
	m_Vertices[1].vertexPos.x = 0.0f;  // Position.
	m_Vertices[1].vertexPos.y = 1.0f;
	m_Vertices[1].vertexPos.z = 0.0f;

	m_Vertices[1].color.x = 0.0f;  // Color.
	m_Vertices[1].color.y = 1.0f;
	m_Vertices[1].color.z = 0.0f;

	// Bottom right.
	m_Vertices[2].vertexPos.x =  1.0f;  // Position.
	m_Vertices[2].vertexPos.y = -1.0f;
	m_Vertices[2].vertexPos.z =  0.0f;

	m_Vertices[2].color.x = 0.0f;  // Color.
	m_Vertices[2].color.y = 0.0f;
	m_Vertices[2].color.z = 1.0f;

	m_IndexBuffer = new uint32[m_NumIndices];
	m_IndexBuffer[0] = 0;
	m_IndexBuffer[1] = 1;
	m_IndexBuffer[2] = 2;
}

le::Model::~Model()
{
	delete[] m_Vertices;
}

void le::Model::InitBuffers()
{
	// Allocate an OpenGL vertex array object.
	glGenVertexArrays(1, &m_VertexBufferId);

	// Bind the vertex array object to store all the buffers and vertex attributes we create here.
	glBindVertexArray(m_VertexBufferId);

	// Generate an ID for the vertex buffer.
	glGenBuffers(1, &m_VertexBufferId);

	// Bind the vertex buffer and load the vertex (position and color) data into the vertex buffer.
	glBindBuffer(GL_ARRAY_BUFFER, m_VertexBufferId);
	glBufferData(GL_ARRAY_BUFFER, m_NumVertices * sizeof(le::Model::VertexType), m_Vertices, GL_STATIC_DRAW);

	// Enable the two vertex array attributes.
	glEnableVertexAttribArray(0);  // Vertex position.
	glEnableVertexAttribArray(1);  // Vertex color.

	// Specify the location and format of the position portion of the vertex buffer.
	glBindBuffer(GL_ARRAY_BUFFER, m_VertexBufferId);
	glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(le::Model::VertexType), 0);

	// Specify the location and format of the color portion of the vertex buffer.
	glBindBuffer(GL_ARRAY_BUFFER, m_VertexBufferId);
	glVertexAttribPointer(1, 3, GL_FLOAT, false, sizeof(le::Model::VertexType), (unsigned char*)NULL + (3 * sizeof(float)));

	// Generate an ID for the index buffer.
	glGenBuffers(1, &m_IndexBufferId);

	// Bind the index buffer and load the index data into it.
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IndexBufferId);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_NumIndices * sizeof(unsigned int), m_IndexBuffer, GL_STATIC_DRAW);
}
